<template>
  <div id="real-time-float"></div>
</template>

<script lang="ts" setup>
  import stomp from "../../../variable/Stomp";
  import * as echarts from "echarts";
  import {onMounted, onUnmounted} from "vue";
  import getThemeConfig from "@/variable/echarts";

  const props = defineProps<{
    id: string
  }>()

  const condition = {
    station: '',
    timeRange: 10,
    sample: 5,
    access: 1
  }

  let data = [];
  let myChart: any
  let option = getThemeConfig();
  const initEcharts = () => {
    const chartDom = document.getElementById('real-time-float')
    if (chartDom == null) {
      return
    }
    chartDom.removeAttribute('_echarts_instance_')
    myChart = echarts.init(chartDom);
    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize)
  }

  const connectStomp = () => {
    stomp.subscribe('/topic/wc', (message) => {
      console.log('/topic/wc')
      if (message.id !== props.id) {
        return
      }
      message.pcList.forEach((pc: object, idx: Number) => {
        if (!data[idx]) {
          data[idx] = []
        }
        for (let i = 0; i < 50; i++) {
          if (i % condition.sample == 0) {
            const value = pc['val' + i]
            data[idx].push([message.startTime * 1000 + 5 * i, value])
            const count = condition.timeRange / 0.005 / condition.sample
            if (data[idx].length > count) {
              data[idx].splice(0, data[idx].length - count)
            }
          }
        }

      })
      const series = []
      const legendData = []
      for (let i = (condition.access == 1 ? 0 : 3); i < (condition.access == 1 ? 3 : 6); i++) {
        series.push({
          data: data[i],
          name: '通道' + (i + 1),
          type: 'line',
          smooth: true,
          symbol: 'none'
        })
        legendData.push('通道' + (i + 1))
      }
      myChart.setOption({
        series,
        legend: {
          data: legendData
        }
      });
    })
  }

  onMounted(() => {
    initEcharts()
    connectStomp()
  })

  onUnmounted(() => {
    window.removeEventListener("resize", myChart?.resize)
    stomp.unsubscribe('/topic/wc')
  })
</script>

<style scoped>
  #real-time-float {
    width: 100%;
    height: 290px;
  }
</style>
